package com.lemon.smartsafetynew.ui.fragment.me;

import android.app.Activity;
import android.content.Intent;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.android.http.HttpUtils;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.ApplicationInfo;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.data.app.DataUtil;
import com.lemon.smartsafety.entity.common.UploadFileItem;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.entity.user.UploadIcon;
import com.lemon.smartsafety.http.HttpOkBase;
import com.lemon.smartsafety.http.HttpPath;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.listener.GlidePauseOnScrollListener;
import com.lemon.smartsafety.result.OldBaseMode;
import com.lemon.smartsafety.result.user.UserIconMode;
import com.lemon.smartsafety.ui.adapter.common.RcvViewType;
import com.lemon.smartsafetynew.ui.fragment.base.BaseLocalListFragment;
import com.lemon.smartsafety.update.UpdateManager;
import com.lemon.smartsafety.utils.CommonUtil;
import com.lemon.smartsafety.utils.ImgLoadUtil;
import com.lemon.smartsafety.utils.JsonUtils;
import com.lemon.smartsafety.utils.LogUtils;
import com.lemon.smartsafety.utils.app.SharedPreferencesServer;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.AppUtils;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.photo.GlideImageLoader;
import com.lemon.smartsafety.view.dialog.DialogChoice;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.AndroidUpdateInfo;
import com.lemon.smartsafetynew.entity.common.CommonBo;
import com.lemon.smartsafetynew.entity.event.EventTagConstants;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.event.me.MeUIEvent;
import com.lemon.smartsafetynew.entity.me.MePanelLabel;
import com.lemon.smartsafetynew.entity.me.MeRcvItemBase;
import com.lemon.smartsafetynew.net.services.AccountServices;
import com.lemon.smartsafetynew.net.services.CommonServices;
import com.lemon.smartsafetynew.ui.activity.me.AboutActivity;
import com.lemon.smartsafetynew.ui.activity.me.ChangePasswordActivity;
import com.lemon.smartsafetynew.ui.activity.me.MeCompanyListActivity;
import com.lemon.smartsafetynew.ui.activity.me.MeModifiedUserNameActivity;
import com.lemon.smartsafetynew.ui.activity.user.UserChangeAccountActivity;
import com.lemon.smartsafetynew.ui.activity.user.UserLoginActivity;
import com.lemon.smartsafetynew.ui.adapter.me.MeFragmentAdapter;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.finalteam.galleryfinal.CoreConfig;
import cn.finalteam.galleryfinal.FunctionConfig;
import cn.finalteam.galleryfinal.GalleryFinal;
import cn.finalteam.galleryfinal.PauseOnScrollListener;
import cn.finalteam.galleryfinal.ThemeConfig;
import cn.finalteam.galleryfinal.model.PhotoInfo;
import kale.adapter.LemonRcvAdapter;

/**
 * Created by Andrew on 2017/7/4.
 */

public class MeFragment extends BaseLocalListFragment<MeRcvItemBase> {

    private List<MePanelLabel> label1;
    private List<MePanelLabel> label2;

    private Activity mContext;


    private MaterialDialog.Builder mMaterialDialog;

    //以下是裁剪
    private SharedPreferencesServer mSharedPreferencesServer;

    private ThemeConfig mThemeConfig = null;
    private FunctionConfig.Builder mFunctionConfigBuilder = null;
    private CoreConfig.Builder mCoreConfigBuilder = null;
    /**
     * 最大的选择照片数量
     */
    private int mMaxSize = 1;
    /**
     * 是否不使用动画
     */
    private boolean bNoAnimation = true;
    private DialogChoice dialogChoice = null;
    private final int REQUEST_CODE_CAMERA = 1000;
    private final int REQUEST_CODE_GALLERY = 1001;
    private final int REQUEST_CODE_CROP = 1002;
    private UploadFileItem uploadFileItem;
    private List<UploadFileItem> uploadFileItemList;
    private Gson mGson;

    //用户头像
    private UserIconMode userIconMode;


    @Override
    public void onPullRefresh() {

    }

    @Override
    public boolean goRefreshOnCreate() {
        return false;
    }

    @Override
    public LemonRcvAdapter<MeRcvItemBase> getLemonAdapter() {
        return new MeFragmentAdapter(mDataList);
    }

    @Override
    protected void initViews() {
        super.initViews();

        mGson = new Gson();
        mContext = getActivity();
        initGalleryFinal();

    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {

        label1 = DataUtil.getMePanelGroupOne();
        label2 = DataUtil.getMePanelGroupTwo();

        mDataList.clear();

        //[我的]页面 用户信息
        User user = AccountUtil.getUser();
        if (user != null) {
            String iconPath = StringUtils.nullValue(HttpUtils.formatFilesUrl(user.getPhotoURL()));
            user.setPhotoURL(iconPath);

            MeRcvItemBase<User> head = new MeRcvItemBase<>();
            head.setViewType(RcvViewType.MeRcvViewType.TYPE_USER_INFO_CARD);
            head.setData(user);
            mDataList.add(head);
        }

        //[我的]页面 组1---主要的操作选项
        MeRcvItemBase<List<MePanelLabel>> list1 = new MeRcvItemBase<>();
        list1.setViewType(RcvViewType.MeRcvViewType.TYPE_GROUP_1_OPTION);
        list1.setData(label1);
        mDataList.add(list1);

        //添加空白的占位行
        MeRcvItemBase head1 = new MeRcvItemBase();
        head1.setViewType(RcvViewType.MeRcvViewType.TYPE_SECTION_HEAD);
        mDataList.add(head1);

        //[我的]页面 组2---主要的操作选项
        MeRcvItemBase<List<MePanelLabel>> list2 = new MeRcvItemBase<>();
        list2.setViewType(RcvViewType.MeRcvViewType.TYPE_GROUP_2_OPTION);
        list2.setData(label2);
        mDataList.add(list2);

        //[我的]页面 退出登录
        MeRcvItemBase<String> btn = new MeRcvItemBase<>();
        btn.setViewType(RcvViewType.MeRcvViewType.TYPE_USER_LOGOUT);
        btn.setData(getString(R.string.profile_exist));
        mDataList.add(btn);

        if (mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(MeUIEvent event) {
        MePanelLabel panelLabel = event.getMePanelLabel();

        if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.CHANGE_PASSWORD) {
            //密码修改
            UIHelper.showActivity(mContext, ChangePasswordActivity.class);
        } else if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.CHANGE_USER_NAME) {
            //用户名修改
            UIHelper.showActivity(mContext, MeModifiedUserNameActivity.class);
        } else if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.SEVER_SETTING) {
            //服务器地址修改
            UIHelper.showUrlSettingActivity(mContext);
        } else if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.APP_UPDATE) {
            //更新升级
            LemonRequestParams params = new LemonRequestParams("");
            params.put("version_code", AppUtils.getVersionCode(IApplication.context()));
            CommonServices.init().updateAppVersion(params);
            //UpdateServices.init().getUpdateInfo(AppUtils.getVersionCode(IApplication.context()));
        } else if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.CHECK_ITEM_BINDING) {
            //检查项目管理
//            User user = AccountUtil.getUser();
//            if(user != null) {
//                CompanyInfo mCompanyInfo = new CompanyInfo();
//                mCompanyInfo.setCompany_code(StringUtils.nullValue(user.getCompanyCode()));
//                mCompanyInfo.setCompany_name(StringUtils.nullValue(user.getCompanyName()));
//                Bundle bundle = new Bundle();
//                bundle.putSerializable(BundleKey.COMPANY_INFO, mCompanyInfo);
//                UIHelper.showSafeDataCollectionCheckItemBuildingList(mContext, bundle);
//            }

            UIHelper.showActivity(mContext, MeCompanyListActivity.class);
        } else if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.APP_ABOUT) {
            //关于
            UIHelper.showActivity(mContext, AboutActivity.class);
        } else if (panelLabel.getMeOptionCode() == ApplicationInfo.MeOptionCodeEnum.CHANGE_USER) {
            //切换用户
            UIHelper.showActivity(mContext, UserChangeAccountActivity.class);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(ViewEvent event) {

        if (EventTagConstants.ME_LOGOUT_TAG.equals(event.getTag())) {
            // ==== 退出登录 ====

            mMaterialDialog = new MaterialDialog.Builder(getActivity())
                    .title(R.string.tip_str_title)
                    .content(R.string.profile_exist_sure)
                    .positiveText(R.string.sure_str)
                    .negativeText(R.string.cancel_str)
                    .onAny(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                            if (which == DialogAction.POSITIVE) {
                                //doExist();
                                Log.i("lala","000000000000000"+mSharedPreferencesHelper.getLoginName());
                                unbindJPush();
                            }
                        }
                    });
            mMaterialDialog.show();

        } else if (EventTagConstants.ME_CHANGE_USER_ICON_TAG.equals(event.getTag())) {
            // ==== 点击头像 ====
            //showActionSheet();
        } else if (EventTagConstants.ME_SETTING_TAG.equals(event.getTag())) {
            // ==== 设置 ====
            //TODO
        }
    }

//    @Subscribe
//    public void onEventMainThread(AppEvent event) {
//        if (SettingUrlActivity.class.getName().equals(event.getTag())) {//SettingUrlActivity 后回传刷新界面  修改了服务器地址，要注销
//            //doExist(); //TODO 我这里是测试的自己的server用的 2017/7/31
//        }
//    }

    /**
     * 解绑
     */
    private void unbindJPush() {
        LemonRequestParams params = new LemonRequestParams("");
        params.put("user_id", AccountUtil.getUserID());
        AccountServices.init().unbindJPush(params, KeyConstants.URL_UNBIND_JPUSH);
    }

    private void doExist() {
        AccountUtil.userLogout();
        Intent mIntent = new Intent(mContext, UserLoginActivity.class);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(mIntent);
    }


    /**
     * 初始化相机工具
     */
    private void initGalleryFinal() {
        mSharedPreferencesServer = new SharedPreferencesServer(IApplication.context());

        mThemeConfig = new ThemeConfig.Builder().setTitleBarBgColor(getResources().getColor(R.color.colorPrimary))
                .setTitleBarTextColor(getResources().getColor(R.color.colorWhite))
                .setTitleBarIconColor(getResources().getColor(R.color.colorWhite))
                .setFabNornalColor(getResources().getColor(R.color.colorPrimary))
                .setCheckSelectedColor(getResources().getColor(R.color.colorPrimary))//选择框选中颜色
                .setFabPressedColor(getResources().getColor(R.color.colorPrimaryDark))
                .build();
        mFunctionConfigBuilder = new FunctionConfig.Builder();
        cn.finalteam.galleryfinal.ImageLoader imageLoader = new GlideImageLoader();
        PauseOnScrollListener pauseOnScrollListener = new GlidePauseOnScrollListener(false, true);
        mFunctionConfigBuilder.setMutiSelectMaxSize(mMaxSize);


        mFunctionConfigBuilder.setEnableEdit(false);
        mFunctionConfigBuilder.setEnableRotate(true);
        mFunctionConfigBuilder.setRotateReplaceSource(false);

        mFunctionConfigBuilder.setEnableCrop(false);
        mFunctionConfigBuilder.setCropReplaceSource(false);
        mFunctionConfigBuilder.setCropSquare(false);
        mFunctionConfigBuilder.setForceCrop(false);//启动强制裁剪功能,一进入编辑页面就开启图片裁剪，不需要用户手动点击裁剪，此功能只针对单选操作
        mFunctionConfigBuilder.setForceCropEdit(false);//在开启强制裁剪功能时是否可以对图片进行编辑（也就是是否显示旋转图标和拍照图标）
        mFunctionConfigBuilder.setEnableCamera(true);
        mFunctionConfigBuilder.setEnablePreview(false);

        mCoreConfigBuilder = new CoreConfig.Builder(IApplication.context(), imageLoader, mThemeConfig).setFunctionConfig(mFunctionConfigBuilder
                .build())
                .setPauseOnScrollListener(pauseOnScrollListener)
                .setNoAnimcation(bNoAnimation);

        mCoreConfigBuilder.setTakePhotoFolder(new File(Environment.getExternalStorageDirectory(), "/DCIM/" + Constants.APP_TEMP_DIR + "/"));

        mCoreConfigBuilder.setEditPhotoCacheFolder(new File(FileUtil.getAppImagesDir(IApplication.context())));

        GalleryFinal.init(mCoreConfigBuilder.build());
    }

    public void showActionSheet() {

        try {
            GalleryFinal.init(mCoreConfigBuilder.build());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (dialogChoice == null) {
            dialogChoice = new DialogChoice(getActivity());
        }

        dialogChoice.init(getActivity(), "取消", new DialogChoice.ClickBackInterface() {
            @Override
            public void callBackFunction(View view, int index) {
                if (index == 0) {//相机
                    mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                    GalleryFinal.openCamera(REQUEST_CODE_CAMERA, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                } else if (index == 1) {
                    mFunctionConfigBuilder.setEnableEdit(false);//这里如果打开了。返回结果后结束视图很慢不知道为什么
                    mFunctionConfigBuilder.setEnableCamera(true);
                    GalleryFinal.openGallerySingle(REQUEST_CODE_GALLERY, mFunctionConfigBuilder.build(), mOnHanlderResultCallback);
                }
            }
        }, "相机", "相册");
    }


    /**
     * 相机或者 相册返回
     */
    private GalleryFinal.OnHanlderResultCallback mOnHanlderResultCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, List<PhotoInfo> resultList) {

            if (!CommonUtil.listIsEmpty(resultList)) {

                LogUtils.LOGE("选择的图片路径：" + resultList.get(0).getPhotoPath());
                GalleryFinal.openCropNew(REQUEST_CODE_CROP, mFunctionConfigBuilder.build(), resultList.get(0).getPhotoPath(), cropCallback);
            }

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            mHUDUtil.setDefault();
            mHUDUtil.showErrorTip(errorMsg);
        }
    };


    /**
     * 裁剪返回
     */
    private GalleryFinal.OnHanlderResultCallback cropCallback = new GalleryFinal.OnHanlderResultCallback() {
        @Override
        public void onHanlderSuccess(int reqeustCode, final List<PhotoInfo> resultList) {

            if (!CommonUtil.listIsEmpty(resultList)) {

                LogUtils.LOGE("裁剪后的路径:" + resultList.get(0).getPhotoPath());
                try {
                    AppService.getBus().post(new UploadIcon(resultList.get(0).getPhotoPath()));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        @Override
        public void onHanlderFailure(int requestCode, String errorMsg) {
            mHUDUtil.setDefault();
            mHUDUtil.showErrorTip(errorMsg);
        }
    };

    /**
     * 上传头像
     */
    @Subscribe
    public void onEventMainThread(final UploadIcon uploadIcon) {

        if (!CommonUtil.strIsEmpty(uploadIcon.getPath())) {
            LogUtils.LOGE("裁剪完待上传图片:" + uploadIcon.getPath());
            getSingleUploadImgBase64(uploadIcon.getPath(), new transBase64CallBack() {
                @Override
                public void onStart() {
                    mHUDUtil.showHUD();
                }

                @Override
                public void onFinish(String data) {
                    if (CommonUtil.strIsEmpty(data)) {
                        mHUDUtil.hidden();
                    } else {
                        httpUploadIcon(data);
                    }
                }
            });
        }

    }


    private void httpUploadIcon(String data) {

        LemonRequestParams params = new LemonRequestParams("user_property_data ", "user_id", "");
        uploadFileItem = new UploadFileItem();
        uploadFileItemList = new ArrayList<>();
        uploadFileItemList.clear();
        uploadFileItem.setBase64(data);
        uploadFileItem.setExt(UploadFileItem.EXT_JPG);
        uploadFileItem.setOp(UploadFileItem.ADD);
        uploadFileItem.setType(UploadFileItem.TYPE_JPG);
        uploadFileItemList.add(uploadFileItem);

        params.put("files", mGson.toJson(uploadFileItemList));
        params.put("handler", "com.ifree.user_verify.UserImgAction");
        params.put("op", "new_save_user_img");
        params.put("_no_html", "1");

        SharedPreferencesServer mSharedPreferencesServer = new SharedPreferencesServer(getActivity());
        String serverUrl = mSharedPreferencesServer.getRequestUrl(HttpPath.ActionServlet_Icon);

        HttpOkBase.httpBasePost(params, serverUrl, "", new HttpOkBase.HttpInterface() {
            @Override
            public void callBackFunction(boolean httpClient, String result) {
                mHUDUtil.hidden();
                if (httpClient) {

                    OldBaseMode baseMode = JsonUtils.fromJson(result, OldBaseMode.class);
                    if (!CommonUtil.objIsEmpty(baseMode)) {
                        if (!baseMode.isIsError()) {

                            try {
                                userIconMode = JsonUtils.fromJson(mGson.toJson(baseMode.getResult()), UserIconMode.class);

                                User user = AccountUtil.getUser();
                                if(user != null) {
                                    user.setPhotoURL(userIconMode.getName());
                                    AccountUtil.saveUser(mGson.toJson(user));

                                    getmContext().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            initData();
                                        }
                                    });

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } else {
                    Log.i("show ", "网络连接失败");
                }
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {

        if (KeyConstants.URL_APP_UPDATE_VERSION.equals(event.getTag())) {                           //版本更新部分逻辑
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    if (event.getObj() instanceof AndroidUpdateInfo) {
                        AndroidUpdateInfo item = (AndroidUpdateInfo) event.getObj();
                        if (null != item) {
                            boolean isForce = CommonBo.Status.status_true.getValue().equals(item.getIs_force());
                            UpdateManager updateManager = new UpdateManager(item.getVersion_remark(), item.getDownload_url(), item
                                    .getVersion_name(), Constants.APP_DOWNLOAD_FILE_NAME, isForce, getActivity());
                            updateManager.checkUpdateInfo();
                        }
                    }
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        } else if(KeyConstants.URL_UNBIND_JPUSH.equals(event.getTag())) {                                                                    //解绑JPush
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.show();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                mHUDUtil.hidden();
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    doExist();
                }
            }
        }
    }



    private interface transBase64CallBack<T> {
        void onStart();
        void onFinish(String data);
    }


    private String tempString;

    private void getSingleUploadImgBase64(final String path, final transBase64CallBack mTransBase64CallBack) {

        if (mTransBase64CallBack == null) {
            return;
        }

        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mTransBase64CallBack != null) {
                    mTransBase64CallBack.onStart();
                }
            }
        });
        if (CommonUtil.strIsEmpty(path)) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mTransBase64CallBack.onFinish("");
                }
            });
            return;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                tempString = "";
                try {
                    tempString = ImgLoadUtil.bitmapToBase64(ImgLoadUtil.getBitmap(path, 70));

                    //tempString = ImageUtils.getImageBase64Code(path);
                    tempString = StringUtils.nullValue(tempString);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mTransBase64CallBack != null) {
                                mTransBase64CallBack.onFinish(tempString);
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        try {
            GalleryFinal.setmCropCallback(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
